package com.third.bank.scheduled;

import com.third.bank.entity.Balance;
import com.third.bank.entity.UserBalanceDaily;
import com.third.bank.service.BalanceService;
import com.third.bank.service.UserBalanceDailyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hm
 * @version 1.0
 * @description TODO
 * @date 2023/4/19 15:58
 */
@Component
public class DailyBalanceRecordTask {
    @Autowired
    private BalanceService balanceService;

    @Autowired
    private UserBalanceDailyService userBalanceDailyService;


    //    @Async
    @Scheduled(cron = "${bank.schedule.dailyRecordTime}")
    public void dailySettlement() {
        // 1、根据当前时间查询所有用户的余额信息
        LocalDateTime now = LocalDateTime.now();
        List<Balance> balanceList = balanceService.getDailyUserList(now);
        // 2、查询当前的利率
        // 3、将用户余额写入用户账户余额日计表
        List<UserBalanceDaily> userBalanceDailyList =
                balanceList.stream()
                           .map(balance -> {
                               UserBalanceDaily userBalanceDaily = new UserBalanceDaily();
                               userBalanceDaily.setUserId(balance.getUserId());
                               userBalanceDaily.setBalance(balance.getBalance());
                               userBalanceDaily.setDateTime(balance.getUpdateTime());
                               return userBalanceDaily;
                           })
                           .collect(Collectors.toList());

        userBalanceDailyService.saveBatch(userBalanceDailyList);
    }

}
